<template>
  <div>
    <!-- 头部区域 -->
    <div class="flex justify-between">
      <h1>产品管理</h1>

      <el-button type="danger" @click="openProductModal">添加产品</el-button>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search_box margin-top">
      <el-form ref="searchFormRef" :model="queryInfo" label-width="120px" class="search-box">
        <!-- <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item prop="goods_name" label="产品名称:">
              <el-input size="large" v-model.trim="queryInfo.goods_name" placeholder="搜索产品名称" :prefix-icon="Search"
                @change="searchTable"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item prop="goods_type_id" label="产品分类:">
              <Select v-model="queryInfo.goods_type_id" mode="api" is-flat labelKey="type_name" valueKey="id" isLevele
                apiUrl="api/admin/typeAddAndEdit" @change="searchTable" />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item prop="status" label="产品状态:">
              <Select v-model="queryInfo.status" :data="productStatus" @change="searchTable" />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <div class="flex justify-end align-center">
              <el-button type="primary" @click="searchTable" size="large">查询</el-button>
              <el-button type="info" :icon="RefreshRight" size="large" @click="resetTable">重置</el-button>
            </div>
          </el-col>
        </el-row> -->

        <div class="flex justify-between align-center">
          <el-form-item prop="goods_name" label="产品名称:">
            <el-input size="large" v-model.trim="queryInfo.goods_name" placeholder="搜索产品名称" :prefix-icon="Search"
              @change="searchTable"></el-input>
          </el-form-item>

          <el-form-item prop="goods_type_id" label="产品分类:">
            <Select v-model="queryInfo.goods_type_id" mode="api" is-flat labelKey="type_name" valueKey="id" isLevele
              apiUrl="api/admin/typeAddAndEdit" @change="searchTable" />
          </el-form-item>

          <el-form-item prop="status" label="产品状态:">
            <Select v-model="queryInfo.status" :data="productStatus" @change="searchTable" />
          </el-form-item>

          <div class="flex justify-end align-center">
            <el-button type="primary" @click="searchTable" size="large">查询</el-button>
            <el-button type="info" :icon="RefreshRight" size="large" @click="resetTable">重置</el-button>
          </div>
        </div>


      </el-form>
    </el-card>

    <el-table ref="multipleTableRef" :data="listData" class="margin-top" style="width: 100%"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />

      <el-table-column property="产品图片" label="产品图片" width="120">
        <template #default="scope">
          <div class="box">
            <el-image :src="scope.row.head_img[0]" />
          </div>
        </template>
      </el-table-column>

      <el-table-column property="goods_name" label="产品名称" width="120" />

      <el-table-column property="goods_money" label="原价" width="400">
        <template #default="scope">
          <div v-for="item in scope.row.prices" :key="item.id">
            <div class="flex align-center price_item">
              <div class="flex align-center">
                <div class="price_name">{{ item.money_name }}</div>

                <div class="margin-left-xs price_value">¥ {{ item.money }}</div>
              </div>

              <div style="color: blue;">折扣价: ¥ {{ item.discount_money }}</div>

              <div class="flex align-center margin-left-sm">
                <el-icon @click="handleProductPrice(scope.row, 'edit', item)">
                  <Edit />
                </el-icon>

                <el-icon class="margin-left-xs" @click="handleGoodsPrice(scope.row, item)">
                  <Delete />
                </el-icon>
              </div>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column property="address" label="分类">
        <template #default="scope">
          <el-tag class="ml-2" type="success">{{ scope.row.goods_type?.type_name }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column property="buy_num" label="销量" />

      <el-table-column property="address" label="状态">
        <template #default="scope">
          <el-tag class="ml-2" type="success" v-if="scope.row.status == 1">上架</el-tag>
          <el-tag class="ml-2" type="info" v-else>下架</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="300">
        <template #default="scope">
          <div class="flex align-center">
            <el-button size="small" @click="openProductModal(scope.row)">编辑</el-button>

            <span class="flex margin-left-xs">
              <el-button size="small" type="success" @click="handleGoodsStatus(scope.row, '1')"
                v-if="scope.row.status == 0">上架</el-button>

              <el-button size="small" type="info" @click="handleGoodsStatus(scope.row, '0')" v-else>下架</el-button>
            </span>

            <el-button class="margin-left-xs" size="small" type="primary"
              @click="handleProductPrice(scope.row, 'add')">添加价格</el-button>

            <el-button class="margin-left-xs" size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="margin-top">
      <Pagination :total="total" @change="changePage" />
    </div>

    <ProductFormModal ref="productFormModalRef" :productStatus="productStatus" @reload="searchTable" />

    <!-- 添加价格弹窗 -->
    <ProductPriceFormModal ref="productPriceFormModalRef" :productStatus="productStatus" @reload="searchTable" />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import Select from '@/components/admin/Select.vue'
import useTableHook from '@/hooks/useTableHook'
import { GoodsList, GoodsAdd, GoodsEdit, GoodsPriceAddAndEdit ,goodsDel} from '@/api/index'
import Pagination from '@/components/admin/Pagination.vue'
import ProductFormModal from '@/components/admin/merchants/ProductFormModal.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import ProductPriceFormModal from '@/components/admin/merchants/ProductPriceFormModal.vue'


// -------------------------
// 商品上下架
const handleGoodsStatus = (record, status) => {
  let statusText = record.status == 1 ? '下架' : '上架'

  ElMessageBox.confirm(`确认${statusText}商品: ${record.goods_name}`, {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  }).then(async () => {
    try {
      let newVal = JSON.parse(JSON.stringify(record))

      newVal.status = status

      const res = await GoodsEdit(newVal)

      ElMessage({
        type: 'success',
        message: `${statusText}成功!`
      })

      searchTable()
    } catch (err) {
      ElMessage({
        type: 'error',
        message: `${statusText}失败!`,
      })
    }
  })
}

const handleDelete = (itme)=>{
	console.log(itme)
	ElMessageBox.confirm(`确认删除?`, {
	  confirmButtonText: '确认',
	  cancelButtonText: '取消',
	}).then(async () => {
	    goodsDel({
	      id: itme.id,
	    }).then(res => {
			if (res.code === 200) {
			  ElMessage('删除成功!')
			    searchTable()
			  return;
			}
		  })
		  .catch(err => {
			console.error('接口失败', err)
		  })

	})

}
// 产品价格 - start
const productPriceFormModalRef = ref(null)

const handleProductPrice = (record, type, goodsPriceData = {}) => {
  goodsPriceData.goodsId = record.id

  productPriceFormModalRef.value?.open({
    params: {
      type,
      goodsPriceData
    }
  })
}

const handleGoodsPrice = (record, item) => {
  ElMessageBox.confirm(`确认删除${record.goods_name}(${item.money_name})的价格`, {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  }).then(async () => {
    try {
      const res = await GoodsPriceAddAndEdit({
        id: item.id,
        method: 'delete',
        goodsId: record.id
      })

      ElMessage('价格删除成功!')

      searchTable()
    } catch (err) {
      ElMessage({
        message: '价格删除失败!',
        type: 'error'
      })
    }
  })
}
// 产品价格 - end
// ---------------------------
// 产品表单模态框状态
const productModalVisible = ref(false)
const currentProduct = ref<any>({})
const isEditMode = ref(false)

// 产品操作处理函数
function handleEditProduct(product: any) {
  console.log('编辑产品:', product)

  // 设置当前编辑的产品
  currentProduct.value = { ...product }

  isEditMode.value = true

  productModalVisible.value = true
}

// 产品表单弹框
const productFormModalRef = ref()

const openProductModal = (record) => {
  // let goods_img = record.head_img && record.head_img[0]

  productFormModalRef.value.open({
    data: {
      ...record,
      goods_img: record.head_img,
    }
  }, true)
}

const productStatus = [
  {
    label: '下架',
    value: 0
  },
  {
    label: '上架',
    value: 1
  }
]

const queryInfo = ref({
  page: 1,
  limit: 10,
  goods_name: '',
  goods_type_id: '',
  status: ''
})

const searchFormRef = ref()

const resetTable = () => {
  searchFormRef.value.resetFields()

  searchTable()
}

onMounted(() => {
  initTable()
})

const { total, changePage, searchTable, listData, initTable } = useTableHook(queryInfo.value, GoodsList)
</script>

<style lang="scss" scoped></style>
